package core;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

import util.TextUtil;

/**
 * A junction has an id.<br>
 * It has the information of the list of objects passing through it during a
 * certain time interval.
 * 
 * @author Xiaohui
 * 
 */
public class Junction extends CheckPoint {
	// first integer is time at which the set of moving objects pass the
	// junction
	// equals zero if going to pass the junction
	// set of integer is set of oid
	HashMap<Integer, Set<Integer>> passTime2Oid;

	public Junction(int id, double[] pCoords) {
		super(id, pCoords);
		passTime2Oid = new HashMap<Integer, Set<Integer>>();
	}

	// public Junction(int id, double[] pCoords,
	// HashMap<Double, Set<Integer>> passTime2Oid) {
	// super(id, pCoords);
	// this.passTime2Oid = passTime2Oid;
	// }

	// public void insertData(TimeInterval ti, int oid) {
	// Set<Integer> li = passTime2Oid.get(ti);
	// if (li == null) {
	// // not created yet
	// Set<Integer> templi = new HashSet<Integer>();
	// templi.add(oid);
	// passTime2Oid.put(ti, templi);
	// } else {
	// // already has a set
	// System.out.println("Adding " + oid);
	// li.add(oid);
	// }
	// }
	public void insertData(Integer i, int oid) {
		Set<Integer> li = passTime2Oid.get(i);
		if (li == null) {
			Set<Integer> templi = new HashSet<Integer>();
			templi.add(oid);
			passTime2Oid.put(i, templi); // i is the time interval
		} else {
			li.add(oid);
		}
	}

	/**
	 * 
	 * @return the number all objects passing through the junction
	 */
	public int getNumPassingObjects() {
		int sum = 0;
		for (Integer ti : passTime2Oid.keySet()) {
			sum += passTime2Oid.get(ti).size();
		}
		return sum;
	}

	public String toString() {
		// System.out.println("junction tostring");
		String retval = getId() + "\t";
		for (double c : m_pCoords) {
			retval += c + "\t";
		}
		for (Integer ti : passTime2Oid.keySet()) {
			retval += ti + "=>" + passTime2Oid.get(ti) + ", ";
		}
		return retval;
	}

	/**
	 * Data to be put into RTree<br>
	 * format: time1 oid1 oid2...; time2 oid1 oid2 ...
	 */
	public String getData() {
		String retval = "";
		Set<Integer> keyset = passTime2Oid.keySet();
		ArrayList<Integer> list = new ArrayList<Integer>(keyset);
		Collections.sort(list);
		for (Integer ti : list) {
			retval += ti + " " + TextUtil.flatenSet(passTime2Oid.get(ti)) + ";";
		}
		list = null;
		return retval;
	}

	public boolean equals(Junction junction) {
		return this.getId() == junction.getId();
	}
	
}
